<template>
	<div class="max">
		<my-header :backBtn="true">
			<div slot="title">
				宝宝食谱
			</div>
			<div slot="right" @click="addDishes" v-if="access!=='kinsfolk'">
				<div>菜色管理</div>
			</div>
			<div slot="right" v-else @click="toShare">
				分享
			</div>
		</my-header>
		<div class="cont-nof">
			<div class="week oh">
				<time-select @onchange="getTime" ref="timeselect" :defaultTime='time' :step="7">
					<div slot="left" style="height: 2rem;line-height: 2rem;">
						<img src="../../../static/img/icon31.png" alt="" style="vertical-align: middle;">
						上一周
					</div>
					<div class="time-block" slot="content">
						{{time[0]}} - {{time[1]}}
					</div>
					<div slot="right" style="height: 2rem;line-height: 2rem;">
						下一周
						<img src="../../../static/img/icon32.png" alt="" style="vertical-align: middle;">
					</div>
				</time-select>
				{{weekInfo.year}}年{{weekInfo.month}}月第{{weekInfo.ofweek}}周({{weekInfo.start}} - {{weekInfo.end}})
			</div>
			<div class="plan oh">
				<template v-if="imgList.length==0&&type!='edit'">
					<template v-if="access!='kinsfolk'">
						<div class="plan_none oh" v-if="type==''">
							<div class="plan_none_icon"></div>
							本周还没有发布食谱哦，快来发布吧！
						</div>
						<div class="add_play oh" v-if="type=='add'">
							<div class="add_title tl">
								点击添加食谱图片
							</div>
							<div class="upload_box">
								<upload-file ref="upload" :type="'image'" :max="1"></upload-file>
							</div>
						</div>
						<div class="add_plan_btn" @click="submit">
							发布
						</div>
					</template>
					<template v-else>
						<div class="plan_none oh">
							<div class="plan_none_icon"></div>
							本周还没有发布食谱哦
						</div>
					</template>
				</template>
				<template v-if="type=='edit'">
					<div class="add_play oh">
						<div class="add_title tl">
							编辑食谱
						</div>
						<div class="upload_box">
							<upload-file ref="upload" :type="'image'" :list="imgList" :max="1"></upload-file>
						</div>
					</div>
					<div class="add_plan_btn" @click="submit">
						确定
					</div>
				</template>
				<template v-if="imgList.length!=0&&type!='edit'">
					<div class="oa" :class="access=='kinsfolk'?'add_play_2':'add_play_3'">
						<div class="add_title tl">
							食谱图片
						</div>
						<div class="upload_box oa">
							<img v-for="item in imgList" @click="previewImage(item.url)" :src="item.url" alt="" width="100%">
						</div>
						<template v-if="access=='kinsfolk'">
							<div class="add_title tl">
								菜色图片
							</div>
							<swiper :options="swiperOption">
								<swiper-slide v-for="(list, index) in foodList" :key="index">
									<div v-for="(item,index2) in list" :key="index2" class="fl" style="width: 33.33%;height:13rem;" @click="previewImage(item.imageList[0].url)">
										<img :src="item.imageList[0].url" alt="" style="width: 10rem;height: 10rem;border-radius: 50%;">
										<div class="tc" style="font-size: 1.2rem;height: 3rem;">
											{{item.name}}
										</div>
									</div>
								</swiper-slide>
							</swiper>
						</template>
					</div>
					<div class="add_plan_btn_2 flex" v-if="access!='kinsfolk'">
						<div @click="deleteCookbook"><img src="../../../static/img/delect.png" alt="">删除</div>
						<div @click="type='edit'"><img src="../../../static/img/bianji.png" alt="">编辑</div>
						<div><img src="../../../static/img/zf.png" alt="" @click="toShare">分享</div>
					</div>
				</template>
			</div>
		</div>
		<div class="weui-mask share" v-if="share" @click="share=false">
			<div class="share_txt">
				点击右上角分享
			</div>
		</div>
	</div>
</template>

<script>
	import timeSelect from '@/components/timeSelect.vue'
	import wx from "weixin-js-sdk";
	import uploadFile from '@/components/uploadFile.vue';

	const fix2 = function(val) {
		if (val < 10) return '0' + val
		else return val
	}
	const getMonthData = function(a, b) {
		//当月1号是周几
		let w = new Date(a, parseInt(b) - 1, 1).getDay();
		if (w == 0) w = 7;
		//第一个周一是几号
		let fw;
		if (w != 1) fw = 7 - w + 2;
		else fw = 1;

		// 当月总天数
		let td = new Date(a, parseInt(b), 0).getDate();

		//当月总共有几周
		let tw = Math.ceil((td - fw + 1) / 7);

		let dateList = []; //日期列表
		let weekList = []; //周列表

		for (let i = fw; i <= td; i++) {
			dateList.push(fix2(i))
		}

		for (let i = 0, len = dateList.length; i < len; i += 7) {
			weekList.push(dateList.slice(i, i + 7));
		}

		for (let i = 0; i < weekList.length; i++) {
			let fill = 7 - weekList[i].length;
			for (let m = 1; m <= fill; m++) {
				weekList[i].push(fix2(m))
			}
		}

		let config = {
			year: a, //年
			month: fix2(b), //月
			first_date_week: fix2(w), //当月1号是周几
			first_week_date: fix2(fw), //当月第一个周一是几号
			total_days: td, //当月总天数
			weekList: weekList, //周列表
		}

		return config
	}
	export default {
		components: {
			timeSelect,
			uploadFile
		},
		data() {
			let time = new Date();
			let year = time.getFullYear();
			let month = time.getMonth() + 1;
			let date = time.getDate();
			return {
				share: false,
				food: {},
				imgList: [],
				type: '',
				time: [year, fix2(month), fix2(date)],
				weekInfo: {},
				monthList: {},
				access: '',
				foodList: [],
				swiperOption: {
					height: 240,
					centeredSlides: false,
					observer: true, //修改swiper自己或子元素时，自动初始化swiper
					observeParents: true, //修改swiper的父元素时，自动初始化swiper
				},
			}
		},
		watch: {
			time(val, oldVal) {
				if (val[0] != oldVal[0]) {
					this.buildMonthList();
				}
			}
		},
		methods: {
			toShare() {
				let imgList = this.imgList;
				if (imgList.length === 0) {
					this.$weui.topTips('暂无可分享的食谱喔');
					return;
				}
				this.share = true;
				let img = imgList.url;
				let kindergartenId = this.food.kindergartenId;
				let year = this.weekInfo.year;
				let month = this.weekInfo.month;
				let ofweek = this.weekInfo.ofweek;
				console.log("http://" + window.location.host + "/wechat/share-food?kindergartenId=" + kindergartenId + "&year=" +
					year + "&month=" + month + "&ofweek=" + ofweek)
				wx.ready(function() { //需在用户可能点击分享按钮前就先调用
					wx.updateTimelineShareData({
						title: year + "年" + month + "月第" + ofweek + "周" + "食谱分享", // 分享标题
						link: "http://" + window.location.host + "/wechat/share-food?kindergartenId=" + kindergartenId + "&year=" +
							year + "&month=" + month + "&ofweek=" + ofweek, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
						imgUrl: img,
						success: function(resp) {
							// 设置成功
							console.log(resp)
						},
						fail: function(re) {
							console.log(re)
						}
					})
				});
			},
			previewImage(url) {
				wx.previewImage({
					previewImage: url,
					urls: [url]
				})
			},
			deleteCookbook() {
				this.$http.deleteCookbook(this.weekInfo).then(resp => {
					this.fetchCookbook();
					this.$weui.toast('删除成功');
				})
			},
			fetchCookbook() {
				this.$http.fetchCookbook(this.weekInfo).then(resp => {
					this.imgList = resp.data.imageList;
					this.food = resp.data;
				})
			},
			addDishes() {
				this.$router.push('/dishes');
			},
			submit() {
				if (this.type == '') {
					this.type = 'add';
				} else {
					this.imgList = this.$refs.upload.getUpList();
					if (this.imgList.length <= 0) {
						this.$weui.topTips('请上传食谱图片');
						return
					}
					let data = Object.assign(this.weekInfo);
					data.imageList = this.imgList
					// 提交
					this.$http.createCookbook(data).then(resp => {
						this.$router.push('/recipe');
						this.type = "";
						this.$weui.toast('保存成功');
					})
				}
			},
			// 设置显示周
			setDuring(index) {
				this.weekInfo.ofweek = index + 1;
				let start = Number(this.weekInfo.weekList[index][0]);
				let end = Number(this.weekInfo.weekList[index][6]);
				let month = Number(this.weekInfo.month);
				this.weekInfo.start = fix2(month) + '.' + fix2(start);
				if (end < start) {
					this.weekInfo.end = fix2(month + 1) + '.' + fix2(end);
				} else {
					this.weekInfo.end = fix2(month) + '.' + fix2(end);
				}
			},
			buildMonthList() {
				for (let i = 1; i < 13; i++) {
					let everyMonth = getMonthData(this.time[0], i);
					this.monthList[everyMonth.month] = everyMonth;
				};
				this.compWeek();
			},
			compWeek() {
				this.weekInfo = this.monthList[this.time[1]];
				let d = Number(this.time[2]);
				let fd = Number(Number(this.weekInfo.first_week_date));
				let month = Number(this.time[1]);
				if (d < fd) { //如果现在的日期小于这个月第一个周一的日期，则这天属于上个月最后一周
					this.weekInfo = this.monthList[fix2(month - 1)];
					this.setDuring(this.monthList[fix2(month - 1)].weekList.length - 1);
				} else {
					let index = parseInt((d - fd) / 7);
					this.setDuring(index);
					this.time[2] = this.weekInfo.weekList[index][0];
				}
			},
			findWeek() {
				this.compWeek();
				this.fetchCookbook();
			},
			getTime(val) {
				if (this.type == "") {
					this.time = val;
					this.findWeek();
				}
			},
			fetchFood() {
				this.$http.fetchFood().then(resp => {
					let data = resp.data.records;
					for (let i = 0; i < data.length; i += 6) {
						this.foodList.push(data.slice(i, i + 6))
					}
				})
			},
			getWxConfig() {
				let url = window.location.href;
				let _this = this;
				_this.$http.fetchWxConfig({
					url: url
				}).then(resp => {
					wx.config({
						// debug: true,
						appId: resp.data.appId,
						timestamp: resp.data.timestamp, // 必填，生成签名的时间戳
						nonceStr: resp.data.noncestr, // 必填，生成签名的随机串
						signature: resp.data.sign, // 必填，签名
						jsApiList: ['updateTimelineShareData'] // 必填，需要使用的JS接口列表
					});
				})
			},
		},
		created() {
			this.fetchFood();
			this.buildMonthList();
			this.access = this.$Cookies.get('loginType');
		},
		mounted() {
			this.fetchCookbook();
			this.getWxConfig();
		}
	}
</script>

<style scoped>
	.week {
		width: 100%;
		height: 9rem;
		margin-bottom: 1.5rem;
		background: #FFFFFF;
		padding: 0.5rem 0;
		box-sizing: border-box;
		font-size: 1.4rem;
	}

	.time-block {
		margin: 0 3rem;
		background: #EBEFF2;
		padding: 0.5rem 1rem;
		font-size: 1.6rem;
		border-radius: 4px;
	}

	.plan {
		height: calc(100% - 10.5rem);
		width: 100%;
		background: #FFFFFF;
		font-size: 1.6rem;
		color: rgba(16, 16, 16, 1);
	}

	.plan_none,
	.add_play {
		height: calc(100% - 10.5rem);
	}

	.plan_none .plan_none_icon {
		position: relative;
		width: 23.2rem;
		height: 13.8rem;
		margin: 8rem auto 6.4rem auto;
		background: url(../../../static/img/xx.png) no-repeat center/contain;
	}

	.plan_none .plan_none_icon::after {
		content: "";
		position: absolute;
		width: 12rem;
		height: 12rem;
		top: 0.9rem;
		left: 6rem;
		background: url(../../../static/img/sp.png) no-repeat center/contain;
	}

	.add_plan_btn {
		margin: 3.5rem auto;
		width: 15rem;
		height: 3.5rem;
		border-radius: 25px;
		background-color: rgba(54, 193, 45, 1);
		color: rgba(255, 255, 255, 1);
		font-size: 2rem;
	}

	.add_title {
		width: 100%;
		font-size: 1.6rem;
		height: 2.4rem;
		line-height: 2.4rem;
		margin: 1.5rem 1rem;
	}

	.upload_box {
		width: calc(100% - 4rem);
		margin: auto;
	}

	.add_play_2 {
		width: 100%;
		height: calc(100% - 3rem);
		overflow-x: hidden;
	}

	.add_play_3 {
		width: 100%;
		height: calc(100% - 5rem);
		overflow-x: hidden;
	}

	.add_plan_btn_2 {
		position: fixed;
		bottom: 0;
		width: 100%;
		height: 5rem;
		border-top: 1px solid rgba(238, 238, 238, 1);
		box-sizing: border-box;
	}

	.add_plan_btn_2>div {
		line-height: 5rem;
		width: 33.333%;
		height: 100%;
		font-size: 1.4rem;
		color: rgba(132, 132, 132, 1);
		border-right: 1px solid rgba(238, 238, 238, 1);
		box-sizing: border-box;
	}

	.add_plan_btn_2>div img {
		width: 1.6rem;
		margin-top: -0.2rem;
		margin-right: 1rem;
		vertical-align: middle;
	}

	.add_plan_btn_2>div:last-child {
		border-right: 0;
	}
</style>
